<template>
  <div class="app-container">
    <!--    因子选择区-->
    <div class="left-board">
      <!--因子类别-->
      <div>
        <el-row class="left-factor-header-list">
          <!-- 因子大类别 -->
          <el-col :span="4" class="components-factorCategory">
            <div v-for="factorCategory in categoryList"
                 :key="factorCategory.factorCategoryId"
                 class="components-factorTitle"
                 @click="getFactorList(factorCategory.factorCategoryId)">
              {{ factorCategory.factorCategoryTitle }}
            </div>
          </el-col>
          <!-- 因子 -->
          <el-col :span="20"
                  style="height: calc(100vh - 90px); overflow: scroll">
            <div v-for="factor in factorList" :key="factor.factorItemTitle"
                 @click="clickFactor(factor)"
                 class="components-item">
              <!--v-if="factor.factorItemTitle!=null"-->
              <el-popover
                style="background:darkgrey"
                placement="top-start"
                width="200"
                trigger="hover"
                :content="factor.factorItemTitle">
                <div class="components-body" slot="reference">
                  {{ factor.factorItemTitle }}
                </div>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--  条件编辑区-->
    <div class="center-board">
      <el-row :gutter="40">
        <el-col :span="15">
          <el-form
            :size="formConf.size"
            :label-position="formConf.labelPosition"
            :disabled="formConf.disabled"
            :label-width="formConf.labelWidth + 'px'">
            <el-form ref="dynamicValidateForm"
                     label-width="120px" class="condition-edit">
              <el-form-item label="因子标题"
                            :rules="[{ required: true, message: '因子标题不能为空', trigger: 'blur' }]">
                <el-input v-model="form.strategyNm" placeholder="请输入因子标题"
                          style="margin-bottom: 10px"/>
              </el-form-item>
              <el-form-item label="因子英文别名"
                            :rules="[{ required: true, message: '因子英文别名不能为空', trigger: 'blur' }]">
                <el-input v-model="form.factorItemEng" placeholder="请输入因子英文别名"
                          style="margin-bottom: 10px" @blur="onchange($event)"/>
              </el-form-item>
              <el-form-item
                prop="email"
                label="因子构造"
                >
                <el-input v-model="form.longText"
                          id="inputFactor"
                          @focus="checkFocus('inputFactor')"
                          placeholder="请输入自定义因子例如： T1=MAX:LY(1),LY(2)"
                          :rules="[{ required: true, message: '因子构造不能为空', trigger: 'blur' }]"
                          type="textarea"
                          :autosize="{ minRows: 7, maxRows: 8}" @keyup.enter.native="KeyUpEsc" @blur="longTextonchange($event)"></el-input>
              </el-form-item>


              <el-divider style="margin: 50px"></el-divider>

              <el-form-item>
                <el-button type="primary" icon="el-icon-document-add"
                           @click="submitForm1">保存因子
                </el-button>
                <el-button @click="resetFormBD">全部清空
                </el-button>
              </el-form-item>
            </el-form>
          </el-form>
        </el-col>
        <el-col :span="9">
          <div class="grid-content bg-purple">
            <el-scrollbar class="operator-list">
              <div class="components-list">
                <draggable
                  class="components-draggable"
                  :list="TbFactorOpList"
                  :group="{ name: 'componentsGroup', pull: 'clone', put: false }"
                  draggable=".components-item"
                  :sort="false"
                >
                  <div
                    v-for="(element, index) in TbFactorOpList" :key="index"
                    class="components-item"
                    @click="clickOpSymbol(element)"
                  >
                    <div class="components-body">
                      <!--                <svg-icon :icon-class="element.tagIcon"/>-->
                      {{ element.symbolNm + ' : ' + element.symbolExpress   }}
                    </div>
                  </div>
                </draggable>
              </div>
            </el-scrollbar>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import {
  listCategory,
  listFactor,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
  verifySom,
  finduserFactorEng,
  finduserFactorverify,
  finduserlongTextUsed,
  addCategorys
} from '@/api/system/useritem'
import draggable from 'vuedraggable'
import ConditionItem from './ConditionItem'
import { listTbFactorOp } from '@/api/system/TbFactorOp'
import { addItem,getItem,updateItem} from "@/api/system/item";


export default {
  components: {
    ConditionItem,
    draggable
  },
  name: 'Category',
  data() {
    return {
      activeName2: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 因子类别表格数据
      categoryList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      strategyNm: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        factorCategoryId: null,
        factorCategoryTitle: null,
        sort: null,
        isdelete: null,
        isdouble: null,
        symbolNm: null,
        symbolExpress: null,
        longText:null,
        symbolTypeCd: null,
        isInvalid: null,
        createTm: null
      },
      // 表单参数
      form: {
        // strategyTmpFactor: '',
        factorItemId:'',
        strategyNm:'',
        factorItemEng:'',
        longText: ''
      },
      // 表单校验
      rules: {},
      //因子类别 id
      factorCategoryId: '',
      //因子列表
      factorList: [],
      //因子名称，用作搜索用
      factorItemTitle: null,

      //
      formConf: {
        formRef: 'elForm',
        formModel: 'formData',
        size: 'medium',
        labelPosition: 'right',
        labelWidth: 100,
        formRules: 'rules',
        gutter: 15,
        disabled: false,
        span: 24,
        formBtns: true
      },
      conditionItemList: [],
      TbFactorOpList: [],
      strategyContentIndex: 0
    }
  },
  watch: {
    // 根据名称筛选因子
    factorItemTitle(val) {
      this.$refs.tree.filter(val)
    }
  },
  activated () {
    if(this.$route.query.factorItemId!=null){
      this.getupdateItem()
    }else {
      this.reset()
    }
  },
  created() {
    this.getList()
    this.getFactorList()
    this.getOperatorList()
    if(this.$route.query.factorItemId!=null){
      this.getupdateItem()
    }
  },
  methods: {
    activeFormItem(element) {
      this.activeData = element
      this.activeId = element.formId
    },
    KeyUpEsc: function() {

      var subStr = this.form.longText.trim().substr(this.form.longText.trim().length-1,1);
      if(subStr!=";")
        this.form.longText=this.form.longText.trim()+";"+"\n";
      // alert(1111);
      var ss=this.form.longText.split(';');
      // alert(ss);
      if(ss[ss.length-2].indexOf(":") == -1){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("伪代码不合法：【没有冒号】");
      }
      if(ss[ss.length-2].indexOf("=") == -1){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("伪代码不合法：【没有等于号】");
      }

      // if(ss[ss.length-2].indexOf("<") == -1&&ss[ss.length-2].indexOf(">") == -1&&ss[ss.length-2].indexOf("=") == -1){
      //   this.form.strategyContent=this.form.strategyContent.trim();
      //   return this.$modal.msgError("伪代码不合法：【没有比较运算符】");
      // }

      // alert(ss[ss.length-2]);
      var bm=ss[ss.length-2].split("=")[0].replace(/\d+/g,'').trim();
      if(bm==""){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("别名不能为纯数字！");
      }
      var data=ss[ss.length-2]
      finduserFactorverify(data).then(response => {
        if (response.msg != '验证成功') {
          this.form.longText=this.form.longText.trim();
          return this.$modal.msgError(response.msg);
        }
        // }else {
        //   this.form.strategyContent=this.form.strategyContent+bm+ss.length+":";
        // }
      });


      // alert(this.form.strategyContent);
    },
    getupdateItem() {
      // this.reset();
      // alert(this.$route.query.factorItemId);
      this.loading = true;
      var factorItemId=this.$route.query.factorItemId;
      // alert(strategyCd);
      getItem(factorItemId).then(response => {
        this.form = response.data;
        this.open = false;
        this.title = "修改自定义因子";
      });
    },
    /** 查询因子类别列表 */
    getList() {
      this.loading = true
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows
        this.total = response.total
        this.loading = false
        // this.conditionItemList = response.rows;
      })
    },
    onchange(event){
      // alert(1111);
      finduserFactorEng(event.target.value).then(response => {
        if (response.msg != '验证成功') {
          return this.$modal.msgError(response.msg);
        }
      })

    },

    longTextonchange(event){
      // alert(1111);
      if(event.target.value=="")
        return;
      finduserlongTextUsed(event.target.value).then(response => {
        if (response.msg != '验证成功') {
          return this.$modal.msgError(response.msg);
        }
      })

    },
    /** 提交按钮 */
    submitForm1() {
      // alert(this.form.strategyContent);
      if (this.form.strategyNm == null || this.form.strategyNm == '') {
        return this.$modal.msgError('因子标题不能为空！')
      }
      if (this.form.factorItemEng == null || this.form.factorItemEng == '') {
        return this.$modal.msgError('因子英文别名不能为空！')
      }

      if (this.form.longText == null || this.form.longText == '') {
        return this.$modal.msgError('因子构造不能为空！')
      }

      var subStr = this.form.longText.trim().substr(this.form.longText.trim().length-1,1);
      if(subStr!=";")
        this.form.longText=this.form.longText.trim()+";"+"\n";
      // alert(1111);
      var ss=this.form.longText.split(';');
      // alert(ss);
      if(ss[ss.length-2].indexOf(":") == -1){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("伪代码不合法：【没有冒号】");
      }
      if(ss[ss.length-2].indexOf("=") == -1){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("伪代码不合法：【没有等于号】");
      }

      // if(ss[ss.length-2].indexOf("<") == -1&&ss[ss.length-2].indexOf(">") == -1&&ss[ss.length-2].indexOf("=") == -1){
      //   this.form.strategyContent=this.form.strategyContent.trim();
      //   return this.$modal.msgError("伪代码不合法：【没有比较运算符】");
      // }

      // alert(ss[ss.length-2]);
      var bm=ss[ss.length-2].split("=")[0].replace(/\d+/g,'').trim();
      if(bm==""){
        this.form.longText=this.form.longText.trim();
        return this.$modal.msgError("别名不能为纯数字！");
      }

      if (this.form.factorItemId != null&&this.form.factorItemId!="") {
        updateItem(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          // this.$store.dispatch('/strategy/strategy', this.$route);
          // this.$router.push('/strategy/strategy');
          // 调用全局挂载的方法
          this.$store.dispatch('tagsView/delView', this.$route)
// /             / 返回上一步路由
          this.$router.go(-1)
        });
      } else {
        addItem(this.form).then(response => {
          console.log('添加策略', this.form, response)
          if (response.msg == '新增成功') {
            this.$modal.msgSuccess(response.msg)
            this.$router.push('/strategy/item');
            // this.$store.dispatch('/strategy/strategy', this.$route);
//             this.$store.dispatch('tagsView/delView', this.$route);
// // /             / 返回上一步路由
//             this.$router.go(-1)
          } else {
            this.$modal.msgError(response.msg)
          }
        })
      }

    },

    // 查询因子列表
    getFactorList(factorCategoryId) {
      if (factorCategoryId == null) {
        factorCategoryId = '100'
      }
      this.loading = true
      this.queryParams.factorCategoryId = factorCategoryId
      listFactor(this.queryParams).then(response => {
        this.factorList = response.rows
        this.loading = false
      })
    },
    //查询运算符列表
    getOperatorList() {
      this.loading = true
      listTbFactorOp(this.queryParams).then(response => {
        this.TbFactorOpList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    //
    checkFocus(e) {
      this.focusId = e
    },
    //点击因子
    clickFactor(item) {
      const elem = document.getElementById(this.focusId)
      const symbol = item.factorItemTitle
      var result = symbol.match(/\(([^)]*)\)/);
      this.insertSomething(elem, result[1]+"(1)")
    },
    //点击运算符
    clickOpSymbol(item) {
      const elem = document.getElementById(this.focusId)
      this.insertSomething(elem, item.symbolExpress)
    },
    //光标后插入内容
    insertSomething(elem, insertStr) {
      const start = elem.selectionStart
      const end = elem.selectionEnd
      const selection = elem.selection
      if (this.focusId === 'inputFactor') {
        let str = this.form.longText
        if (str == null || str === '') {
          this.form.longText = insertStr
        } else {
          this.form.longText = str.slice(0, start) + insertStr + str.slice(end)
        }
      } else if (this.focusId === 'inputCondition') {
        let str = this.form.strategyContent
        if (str == null || str === '') {
          this.form.strategyContent =  insertStr
        } else {
          this.form.strategyContent = str.slice(0, start) + insertStr + str.slice(end)
        }
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    resetFormBD() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        factorCategoryId: null,
        factorCategoryTitle: null,
        sort: null,
        isdelete: null,
        strategyNm: null,
        isdouble: null,
        longText:null,
        strategyLogic: null,
        // strategyTmpFactor: null,
        strategyContent: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.factorCategoryId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    //重置
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    }
  }
}
</script>

<style lang='scss' scoped>

$selectedColor: #f6f7ff;



.app-container {
  height: calc(100vh - 80px);
  width: 100%;
  padding: 10px;
  display: flex;
}

.left-board {
  width: 360px;
  height: calc(100vh - 80px);
}

.left-factor-header-list {
  display: flex;
  height: calc(100vh - 80px);

  .components-factorCategory {
    background: #F0F1FF;
    height: calc(100vh - 80px);;
    box-shadow: 1.5px 0 1px #E6E8FF;
  }

  //
  .components-factorTitle {
    font-size: 13px;
    font-weight: bold;
    color: #222;
    text-align: center;
    margin-top: 10px;
    flex: 1;

    &:hover {
      color: #787be8;
      background: #E6E8FF;
    }
  }

  .components-item {
    display: inline-block;
    width: 48%;
    margin: 1%;
    transition: transform 0ms !important;
  }
}


.components-body {
  padding: 8px 10px;
  background: $selectedColor;
  font-size: 12px;

  .svg-icon {
    color: #777;
    font-size: 15px;
  }

  &:hover {
    color: #787be8;
    background: #E6E8FF;
    border-radius: 3px;
  }
}

.center-board {
  height: 100%;
  padding: 0 10px;
  flex: 1;
  display: flex;
  //padding: 10px;

  .components-list {
    padding: 8px;
    box-sizing: border-box;
    height: 100%;

    .components-item {
      display: inline-block;
      width: 48%;
      margin: 1%;
      transition: transform 0ms !important;
    }
  }

  .components-body {
    padding: 8px 10px;
    background: $selectedColor;
    font-size: 12px;
    cursor: default;
    border: 1px dashed $selectedColor;
    border-radius: 3px;
  }

  .el-row {
    margin-bottom: 20px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .operator-list {
    height: calc(100vh - 80px);
    //overflow: hidden;
  }

  //.action-button {
  //  display: flex;
  //  justify-content: space-between;
  //}
}


//
//$selectedColor: #f6f7ff;
//$lighterBlue: #409EFF;
//
//.custom {
//  width: 40%;
//  border: 1px red solid;
//  margin-left: 500px;
//}
//
////
////ol {
////  counter-reset: item;
////  margin-left: 0;
////  padding-left: 0;
////}
////li {
////  display: block;
////  margin-bottom: .5em;
////  margin-left: 3em;
////}
////li::before {
////  display: inline-block;
////  content: "C" counter(item) ": ";
////  counter-increment: item;
////  width: 3em;
////  margin-left: -3em;
////}
//
//.right-board {
//  width: 60%;
//  padding-left: 450px;
//  padding-top: 10px;
//  height: 50%;
//}
//

//

//
//
//.drawing-board {
//  height: 100%;
//  position: relative;
//
//  .components-body {
//    padding: 0;
//    margin: 0;
//    font-size: 0;
//  }
//
//  .sortable-ghost {
//    position: relative;
//    display: block;
//    overflow: hidden;
//
//    &::before {
//      content: " ";
//      position: absolute;
//      left: 0;
//      right: 0;
//      top: 0;
//      height: 3px;
//      background: rgb(89, 89, 223);
//      z-index: 2;
//    }
//  }
//
//  .components-item.sortable-ghost {
//    width: 100%;
//    height: 60px;
//    background-color: $selectedColor;
//  }
//
//  .active-from-item {
//    & > .el-form-item {
//      background: $selectedColor;
//      border-radius: 6px;
//    }
//
//    & > .drawing-item-copy, & > .drawing-item-delete {
//      display: initial;
//    }
//
//    & > .component-name {
//      color: $lighterBlue;
//    }
//  }
//
//  .el-form-item {
//    margin-bottom: 15px;
//  }
//}
//
//.empty-info {
//  position: absolute;
//  top: 46%;
//  left: 0;
//  right: 0;
//  text-align: center;
//  font-size: 18px;
//  color: #ccb1ea;
//  letter-spacing: 4px;
//}

</style>
